package com.imooc.reader.management.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.reader.management.dto.ResponseDTO;
import com.imooc.reader.management.entity.User;
import com.imooc.reader.management.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("")
    public ResponseDTO selectByRoleCode(Integer page,Integer rows){
        if(page == null){
            page = 1;
        }
        if(rows == null){
            rows = 10;
        }
        IPage<User> p = userService.selectByRoleCode(new Page(page, rows), "USER");
        for(User u : p.getRecords()){
            u.setPassword(null);
        }
        return new ResponseDTO().put("list", p.getRecords()).put("count", p.getTotal());
    }

    @PostMapping("")
    public ResponseDTO createUser(String username, String password , String empName , String deptName){
        User user = userService.createUser(username, password, empName, deptName);
        user.setPassword(null);
        return new ResponseDTO().put("user",user);
    }


    @PutMapping("/{userId}")
    public ResponseDTO updateBasicInfo(@PathVariable("userId") Integer userId, String empName, String deptName){
        User user = userService.updateBasicInfo(userId, empName, deptName);
        user.setPassword(null);
        return new ResponseDTO().put("user",user);
    }
    @PutMapping("/{userId}/status")
    public ResponseDTO updateStatus(@PathVariable("userId") Integer userId) {
        User user = userService.updateStatus(userId);
        user.setPassword(null);
        return new ResponseDTO().put("detail",user.getUsername() + "已" + (user.getStatus()==1?"启用":"停用"));
    }
    @DeleteMapping("/{userId}")
    public ResponseDTO deleteUser(@PathVariable("userId") Integer userId){
        User user = userService.deleteUser(userId);
        user.setPassword(null);
        return new ResponseDTO().put("user",user);
    }
}
